<!--
 * @Description: 菜单二级tabs
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2022-12-24 11:11:35
 * @LastEditTime: 2022-12-24 16:49:51
 * @FilePath: \cscec-pms-admin\src\layouts\MenuTabs.vue
-->
<template>
  <ul
    class="menu-tabs"
    ref="menuTabs"
  >
    <template v-if="collapsed">
      <li
        v-for="item in data"
        :key="item.code"
        @click="currentValue = item.code"
        :style="'width:calc(100% / ' + data.length + ')'"
      >
        {{ item.name }}
      </li>
    </template>
    <li v-else>
      {{ !!currentValue ? data.find(el=>el.code === currentValue).name : '' }}
    </li>
    <div
      class="active"
      :style="'width:calc(100% / ' + (collapsed ? data.length : 1) + ');left:' + offsetX + 'px;'"
    />
  </ul>
</template>
<script>
export default {
  name: 'MenuTabs',
  props: {
    // 列表
    list: {
      type: Array,
      default: () => []
    },
    // 选中值
    value: {
      type: String,
      default: ''
    },
    // 菜单是否展开
    collapsed:{
      type: Boolean,
      require: true
    }
  },
  data() {
    return {
      // 当前选中横向偏移量
      offsetX: 0
    }
  },
  computed: {
    // 当前值
    currentValue: {
      get: function () {
        return this.value
      },
      set: function (value) {
        this.$emit('input', value)
      }
    },
    // 列表
    data() {
      return this.list.map((el) => {
        return {
          code: el.raw.code,
          name: el.raw.name
        }
      })
    }
  },
  watch: {
    // 选中值改变获取偏移量
    currentValue: {
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.offsetX = this.getOffsetX()
          })
        }
      }
    },
    // 展开收起菜单获取偏移量
    collapsed:{
      handler(){
        this.$nextTick(() => {
          let timer = setTimeout(()=>{
            this.offsetX = this.getOffsetX()
            clearTimeout(timer)
            timer = void 0
          },150)
        })
      }
    }
  },
  methods: {
    /**
     * @description: 获取当前选中横向偏移量
     * @return {number}
     */
    getOffsetX() {
      if(this.$refs.menuTabs){
        const w = this.$refs.menuTabs.offsetWidth / this.data.length
        const i = this.data.findIndex((el) => el.code === this.value)
        return this.collapsed ? (i < 0 ? 0 : i) * w : 0
      }else{
        return 0
      }
    }
  }
}
</script>
<style lang="less" scoped>
.menu-tabs {
  background-color: #fff;
  display: flex;
  flex-wrap: nowrap;
  padding: 16px 0;
  margin: 0;
  position: relative;
  overflow: hidden;
  li {
    height: 50px;
    text-align: center;
    line-height: 50px;
    cursor: pointer;
    width: 100%;
  }
  .active {
    position: absolute;
    top: 16px;
    height: 50px;
    background: url(../assets/businessTabBg.png) no-repeat;
    background-size: 100% 100%;
    cursor: default;
    transition: all 0.5s ease;
  }
}
</style>
